library ieee;
use ieee.std_logic_1164.all;
use ieee.std_logic_unsigned.all;

entity timer is
	generic (
		-- counter size, or maximum period (in bits)
		size		: in  positive
	);
	port ( 
		-- system clock
		clk			: in  std_logic; 
		-- system reset
		reset		: in  std_logic;
		-- unsigned integer, a pulse is generated
		--   every 'period' clockcycles
		period	: in  std_logic_vector(size-1 downto 0);
		-- the generated pulse (AH)
		pulse		: out std_logic
	);
end entity;

architecture behaviour of timer is
   -- counter register
   signal counter : std_logic_vector(size-1 downto 0);
	-- counter reset signal	(on period reached)
   signal counter_reset : std_logic;
   -- zero signal for comparison
   signal zero					: std_logic_vector(size-1 downto 0);
begin
	zero <= (others => '0');
	counter_reset <= '1' when counter > period and not (period = zero) else '0';
	pulse <= counter_reset;

	-- counter
	process(clk, reset, counter_reset)	begin
		if (clk'event and clk = '1') then
			if (counter_reset = '1' or reset = '1') then
				-- start at two, since it resets on period+1 (not period-1), this makes the
				-- comperator somewhat smaller (> instead of >=)
				counter(size-1 downto 2) <= (others => '0');
				counter(1) <= '1';
				counter(0) <= '0';
			else 
				counter <= counter + 1;
			end if;
		end if;
	end process;

end architecture;
